package bman.tools.net;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Logger;

/**
 * This is a component used by of the Radio class. Don't bother much with this.
 *  
 * The job of this class is to listen to incoming connections and create SocketListeners 
 * for each one.
 * 
 * The port passed in the constructor of this class is the port where 
 * the Radio (who owns this ServerSocketListener) is listening to.
 * 
 * @author MrJacky
 *
 */
public class ServerSocketListener extends Thread 
{
	static Logger log = Logger.getLogger(ServerSocketListener.class.getName()); 
	
	ServerSocket ss;
	Receiver m_Receiver;
	Radio radio;
	
	boolean run = true;
	
	public ServerSocketListener(int port, Receiver Receiver, Radio radio) throws Exception
	{
		ss = new ServerSocket(port);
		m_Receiver = Receiver;
		this.radio = radio;
		start();
	}
	
	public void run()
	{
		log.info("Starting SocketListener...");
		
		while(run)
		{
			try
			{
				Socket s = ss.accept();
				radio.addSocket(s);
				String address = s.getInetAddress().getHostAddress();
				log.info("Adding socket connection: "+ address);
				new SocketListener(s,m_Receiver);
			}
			catch(Exception e)
			{
				log.warning("Error in accepting new socket connection.");
				e.printStackTrace();
			}
		}
	}
}
